package com.example.jdai.jdai.ui;

import android.app.Activity;
import android.content.IntentFilter;
import android.support.v7.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.example.jdai.jdai.MyApplication;
import com.example.jdai.jdai.R;
import com.example.jdai.jdai.config.Config;
import com.example.jdai.jdai.rest.BackRest;
import com.example.jdai.jdai.rest.GetData;
import com.example.jdai.jdai.rest.bean.PayResult;
import com.example.jdai.jdai.threeparty.SmsReceiver;
import com.example.jdai.jdai.threeparty.UpdataService;
import com.example.jdai.jdai.util.DataAll;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.util.Map;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginActivity extends Activity implements BackRest.DoLong {
    private static final int SDK_PAY_FLAG = 1;

    @BindView(R.id.tb)
    TopBar tb;
    @BindView(R.id.et_num)
    EditText etNum;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.bt_login)
    Button btLogin;
    @BindView(R.id.activity_login)
    LinearLayout activityLogin;
    @BindView(R.id.my_yzm)
    MyYzm myYzm;
    ProgressDialog pd;
    @BindView(R.id.tv_regist)
    TextView tvRegist;
    @BindView(R.id.tv_ed)
    TextView tvEd;
    @BindString(R.string.forcheck_tip)
    String forCheckTip;
    @BindString(R.string.no_complete)
    String nocomplete;
    SmsReceiver mSMSBroadcastReceiver;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            @SuppressWarnings("unchecked")
            PayResult payResult = new PayResult((Map<String, String>) msg.obj);
            /**
             对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
             */
            String resultInfo = payResult.getResult();// 同步返回需要验证的信息
            String resultStatus = payResult.getResultStatus();
            // 判断resultStatus 为9000则代表支付成功
            if (TextUtils.equals(resultStatus, "9000")) {
                // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                Toast.makeText(LoginActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                pd.show();
                MyApplication.backRest.login(LoginActivity.this, etNum.getText().toString().trim(),
                        etCode.getText().toString().trim());

            } else {
                // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                Toast.makeText(LoginActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
            }
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        pd = new ProgressDialog(this);
        pd.setMessage("正在登入...");
        pd.setCanceledOnTouchOutside(false);
        myYzm.setMyYzmClick(new MyYzm.MyYzmClick() {
            @Override
            public boolean click() {
                if ("".equals(etNum.getText().toString().trim())) {
                    return false;
                }
                if(etNum.length()!=11) {
                    Toast.makeText(MyApplication.applicationContext, "手机号不正确", Toast.LENGTH_SHORT).show();
                    return false;
                }
                MyApplication.backRest.smsOk(etNum.getText().toString().trim(),myYzm);
                return true;
            }
        });
        tb.setTopBarLisener(new TopBar.TopBarLisener() {
            @Override
            public void back() {
                startActivity(new Intent(LoginActivity.this,RegistActivity.class));
                finish();
            }

            @Override
            public void more() {

            }
        });
        initView();
        smsGet();
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK) {
            startActivity(new Intent(LoginActivity.this, RegistActivity.class));
            finish();
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(mSMSBroadcastReceiver);
    }

    @OnClick({R.id.bt_login,R.id.tv_regist})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_login:
                if (chechAll()) {
                    pd.show();
                    MyApplication.backRest.login(LoginActivity.this, etNum.getText().toString().trim(),
                            etCode.getText().toString().trim());
                }
                break;
            case R.id.tv_regist:
                startActivity(new Intent(LoginActivity.this,RegistActivity.class));
                finish();
        }
    }

    @Override
    public void doDone(int mark, Map str) {
        switch (mark) {
            case 999:
                pd.dismiss();
                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                finish();
                break;
            case 1:
                pd.dismiss();
                startActivity(new Intent(LoginActivity.this, ScActivity.class));
                finish();
                break;
            case 2:
                Toast.makeText(MyApplication.applicationContext, "出现错误", Toast.LENGTH_SHORT).show();
                pd.dismiss();
                break;
            case 201:
                Toast.makeText(MyApplication.applicationContext, "验证码错误", Toast.LENGTH_SHORT).show();
                pd.dismiss();
                break;
            case 206:
                Toast.makeText(MyApplication.applicationContext, "账户需要激活", Toast.LENGTH_SHORT).show();
                pd.dismiss();
               forJiHuo();
                break;
            case 666:
                final String orderInfo= (String) str.get("order");
                Runnable payRunnable = new Runnable() {
                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(LoginActivity.this);
                        Map<String, String> result = alipay.payV2(orderInfo, true);
                        if(Config.ISDEBUG)
                            Log.i("msp", result.toString());
                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };

                Thread payThread = new Thread(payRunnable);
                payThread.start();
                break;
            case 203:
                Toast.makeText(MyApplication.applicationContext, "账户不存在", Toast.LENGTH_SHORT).show();
                pd.dismiss();
                break;




        }

    }
//    //获得验证码
//    void getCode(){
//        RestApi.CodeService service = MyApplication.retrofit.create(RestApi.CodeService.class);
//        SendCode send=new SendCode ();
//        send.data.put("tel",etNum.getText().toString().trim());
//        service.getCode(RestApi.getBody(send))
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Subscriber<GetData<String>>() {
//                    @Override
//                    public void onCompleted() {
//                        if (Config.ISDEBUG)
//                        Log.v("login","complete");
//                    }
//                    @Override
//                    public void onError(Throwable e) {
//                        if (Config.ISDEBUG)
//                        Log.v("login",e.toString());
//
//                    }
//                    @Override
//                    public void onNext(GetData<String> stringStringMap) {
//                        if (Config.ISDEBUG)
//                        Log.v("login",new GsonBuilder().setPrettyPrinting().create().toJson(stringStringMap));
//
//                    }
//                });
//
//    }


//        service.login(RestApi.getBody(send)).subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Subscriber<GetData<LoginBean>>() {
//                    @Override
//                    public void onCompleted() {
//                        if (Config.ISDEBUG)
//                        Log.v("login","complete");
//                    }
//                    @Override
//                    public void onError(Throwable e) {
//                        Toast.makeText(LoginActivity.this,"验证码或用户名有误",Toast.LENGTH_SHORT).show();
//                    }
//                    @Override
//                    public void onNext(GetData<LoginBean> stringStringMap) {
//                        if (Config.ISDEBUG)
//                        Log.v("login",new GsonBuilder().setPrettyPrinting().create().toJson(stringStringMap));
//                       // Log.v("sss",new GsonBuilder().setPrettyPrinting().create().toJson(stringStringMap.getData().getUser_info()));
//                        MyApplication.dataAll.data.put(DataAll.LOGIN_TOKEN,stringStringMap.getData().getUser_info().getToken());
//                        MyApplication.dataAll.data.put(DataAll.HAS_LOGIN,etNum.getText().toString().trim());
//                        MyApplication.dataAll.data.put(DataAll.LOGIN_ID,stringStringMap.getData().getUser_info().getId()+"");
//                        MyApplication.dataAll.data.put(DataAll.IS_COMMIT,stringStringMap.getData().getVerify_info().getIs_commit());
//                        saveData(stringStringMap.getData().getVerify_info());
//                        MyApplication.dataAll.saveAll();
//                        if(!"0".equals(stringStringMap.getData().getVerify_info().getIs_commit())){
//                        startActivity(new Intent(LoginActivity.this,MainActivity.class));
//                        finish();}
//                        else {
//                            startActivity(new Intent(LoginActivity.this,ScActivity.class));
//                            finish();
//                        }
//                    }
//                });
//
void forJiHuo(){
    final AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
    //    设置Title的图标
    builder.setIcon(R.drawable.logo1);
    builder.setTitle("账户需要激活");
    builder.setMessage(forCheckTip);
    //    设置一个PositiveButton
    builder.setPositiveButton("同意", new DialogInterface.OnClickListener()
    {
        @Override
        public void onClick(DialogInterface dialog, int which)
        {
            MyApplication.backRest.getOrder(LoginActivity.this,etNum.getText().toString().trim());
        }
    }).setNegativeButton("取消",null);
    builder.show();
}
    void initView(){
        tvEd.setText(MyApplication.dataAll.data.get(DataAll.MY_MONEY));
    }
    public boolean chechAll() {
        if (TextUtils.isEmpty(etNum.getText().toString().trim()) ||
                TextUtils.isEmpty(etCode.getText().toString().trim())) {
            Toast.makeText(MyApplication.applicationContext, nocomplete, Toast.LENGTH_SHORT).show();
            return false;
        }
        if(etNum.length()!=11) {
            Toast.makeText(MyApplication.applicationContext, "手机号不正确", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }
    void smsGet(){
         mSMSBroadcastReceiver = new SmsReceiver();
        //实例化过滤器并设置要过滤的广播
        IntentFilter intentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
        intentFilter.setPriority(Integer.MAX_VALUE);
        //注册广播
        this.registerReceiver(mSMSBroadcastReceiver, intentFilter);
        mSMSBroadcastReceiver.setOnReceivedMessageListener(new SmsReceiver.MessageListener() {
            @Override
            public void onReceived(String message) {
             etCode.setText(message);
                }
            });
    }

}
